package com.china08.yxyapi.service.manage.tec.teaching.homework.workcorrect1.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.china08.yxyapi.api.manage.tec.teaching.homework.worklist.workcorrect1.Workcorrect1FindClassStuTaskController.RespModel;
import com.china08.yxyapi.api.manage.tec.teaching.homework.worklist.workcorrect1.Workcorrect1FindClassStuTaskController.Student;
import com.china08.yxyapi.entity.mg.homework.HomeworkKnowReport;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskClass;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskReport;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskReportQues;
import com.china08.yxyapi.repository.mg.homework.HomeworkKnowReportRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskClassRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskQuesRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskReportQuesRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskReportRepository;
import com.china08.yxyapi.service.manage.tec.teaching.homework.workcorrect1.HomeworkCorrect1Service;

@Service(value = "HomeworkCorrectv1ServiceImpl")
public class HomeworkCorrect1ServiceImpl implements HomeworkCorrect1Service {

    @Autowired
    HomeworkTaskReportQuesRepository homeworkTaskReportQuesRepository;

    @Autowired
    HomeworkTaskReportRepository homeworkTaskReportRepository;

    @Autowired
    HomeworkTaskClassRepository homeworkTaskClassRepository;

    @Autowired
    HomeworkTaskQuesRepository homeworkTaskQuesRepository;

    @Autowired
    HomeworkKnowReportRepository homeworkKnowReportRepository;

    @Override
    public RespModel convertRespModel(HomeworkTaskClass homeworkTaskClass,
            List<HomeworkTaskReport> homeworkTaskReports) {
        // return
        RespModel respModel = new RespModel();
        List<Student> classStuTaskReports = new ArrayList<Student>();
        // ##
        respModel.taskName = homeworkTaskClass == null ? "" : homeworkTaskClass.getTitle();
        respModel.grade = "";
        respModel.className = homeworkTaskClass == null ? "" : homeworkTaskClass.getClassName();
        respModel.predictDateTimeStamp = homeworkTaskClass == null ? 0l : homeworkTaskClass.getPredictDate().getTime();

        // 手工排序，按照学生完成时间排序，-1-逾期未提交,0-未做,3-答题中 排在后面，1-完成 ,2-已批阅排在前面
        List<HomeworkTaskReport> list1 = new ArrayList<>(); // 1-完成 ,2-已批阅
        List<HomeworkTaskReport> list2 = new ArrayList<>(); // 3-答题中
        List<HomeworkTaskReport> list3 = new ArrayList<>(); // -1-逾期未提交,0-未做
        homeworkTaskReports.forEach(homeworkTaskReport -> {
            if (homeworkTaskReport.getStatusOfFinished() == 1 || homeworkTaskReport.getStatusOfFinished() == 2) {
                list1.add(homeworkTaskReport);
            } else if (homeworkTaskReport.getStatusOfFinished() == 3) {
                list2.add(homeworkTaskReport);
            } else if (homeworkTaskReport.getStatusOfFinished() == -1
                    || homeworkTaskReport.getStatusOfFinished() == 0) {
                list3.add(homeworkTaskReport);
            }
        });
        // return
        list1.forEach(homeworkTaskReport -> {
            Student classStuTaskReport = new Student();
            classStuTaskReport.studentId = homeworkTaskReport.getStudentId();
            classStuTaskReport.studentNick = homeworkTaskReport.getStudentNick();
            classStuTaskReport.studentImg = homeworkTaskReport.getAvatar();
            classStuTaskReport.statusOfFinished = homeworkTaskReport.getStatusOfFinished();
            classStuTaskReports.add(classStuTaskReport);
        });
        list2.forEach(homeworkTaskReport -> {
            Student classStuTaskReport = new Student();
            classStuTaskReport.studentId = homeworkTaskReport.getStudentId();
            classStuTaskReport.studentNick = homeworkTaskReport.getStudentNick();
            classStuTaskReport.studentImg = homeworkTaskReport.getAvatar();
            classStuTaskReport.statusOfFinished = homeworkTaskReport.getStatusOfFinished();
            classStuTaskReports.add(classStuTaskReport);
        });
        list3.forEach(homeworkTaskReport -> {
            Student classStuTaskReport = new Student();
            classStuTaskReport.studentId = homeworkTaskReport.getStudentId();
            classStuTaskReport.studentNick = homeworkTaskReport.getStudentNick();
            classStuTaskReport.studentImg = homeworkTaskReport.getAvatar();
            classStuTaskReport.statusOfFinished = homeworkTaskReport.getStatusOfFinished();
            classStuTaskReports.add(classStuTaskReport);
        });
        respModel.students = classStuTaskReports;
        return respModel;
    }

    @Override
    public void correct(String taskId, String classId, String studentId) {
        // 单选题、多选题数量
        List<String> quesTypes = new ArrayList<>();
        quesTypes.add("0");
        quesTypes.add("1");
        Integer total0_1 = homeworkTaskQuesRepository.countByTaskIdAndQuesTypeIn(taskId, quesTypes);
        total0_1 = total0_1 == null ? 0 : total0_1;
        
        // 批阅主观题数量
        List<String> quesTypes3_4 = new ArrayList<>();
        quesTypes3_4.add("3");
        quesTypes3_4.add("4");
        Integer total3_4 = homeworkTaskQuesRepository.countByTaskIdAndQuesTypeIn(taskId, quesTypes3_4);
        total3_4 = total3_4 == null ? 0 : total3_4;
        
        // 批阅通知类试题数量【忽略不要学生作答通知试题】
        Integer total2 = homeworkTaskQuesRepository.countByTaskIdAndQuesTypeAndIfNeedSumbit(taskId, "2", true);
        total2 = total2 == null ? 0 : total2;
        
        // 阅读类试题数量
        Integer total5 = homeworkTaskQuesRepository.countByTaskIdAndQuesType(taskId, "5");
        total5 = total5 == null ? 0 : total5;
    	
    	// 本次任务需要统计试题数量【忽略不要学生作答通知试题】
    	// 单选题、多选题、填空题、简单题、通知题【需要学生作答】、阅读题
        Integer total = total0_1 + total3_4 + total2 + total5;
    	
    	// 本地任务需要批阅试题数量
    	// 填空题、简单题、通知题【需要学生作答】、阅读题
        Integer total3_4_2_5 = total3_4 + total2 + total5;
    	
        // 需要统计试题数量 > 0
        if (total != null && total > 0) {
        	// ##
            // 需要批阅试题数量为 0
            if (total3_4_2_5 == 0) {
            	// 修改状态
            	this.correctUpd(taskId, classId, studentId, total);
            // ##
            // 本次任务有 主观题或通知作业
            } else {
                // 教师批阅主观题数量
                List<String> quesTypes3_4_ = new ArrayList<>();
                quesTypes3_4_.add("3");
                quesTypes3_4_.add("4");
                Integer total3_4_ = homeworkTaskReportQuesRepository
                        .countByClassIdAndStudentIdAndTaskIdAndQuestionTypeInAndMarkNot(classId, studentId, taskId,
                        		quesTypes3_4_, null);
                total3_4_ = total3_4_ == null ? 0 : total3_4_;
                
                // 教师批阅通识类试题数量【忽略不要学生作答通知试题】
                Integer total2_ = 0;
                if (total2 > 0) {
                	total2_ = homeworkTaskReportQuesRepository
                    		.countByClassIdAndStudentIdAndTaskIdAndQuestionTypeAndMarkNot(classId, studentId, taskId,
                    				"2", null);
                }
                total2_ = total2_ == null ? 0 : total2_;
                
                // 教师批阅阅读类试题数量
                Integer total5_ = homeworkTaskReportQuesRepository
                        .countByClassIdAndStudentIdAndTaskIdAndQuestionTypeAndMarkNot(classId, studentId, taskId,
                                "5", null);
                total5_ = total5_ == null ? 0 : total5_;
                
            	// 教师是否批阅完成
                if ((total3_4_ + total2_ + total5_) == total3_4_2_5) {
                	// 修改状态
                	this.correctUpd(taskId, classId, studentId, total);
                }
            }
        }
    }

    // 修改状态
    private void correctUpd(String taskId, String classId, String studentId, int total) {
    	// 获取学生作业记录
        HomeworkTaskReport homeworkTaskReport = homeworkTaskReportRepository
                .findTop1ByTaskIdAndClassIdAndStudentId(taskId, classId, studentId);
        // 获取班级任务
        HomeworkTaskClass homeworkTaskClassz = homeworkTaskClassRepository
                .findTop1ByTaskIdAndClassId(taskId, classId);
        try {
            // 更新学生任务完成状态为 -> 批阅
            homeworkTaskReport.setStatusOfFinished(2);
            homeworkTaskReportRepository.save(homeworkTaskReport);
            // 更新班级批阅人数
            homeworkTaskClassz.setMarkingOfStudent(homeworkTaskReportRepository
                    .countByClassIdAndTaskIdAndStatusOfFinished(classId, taskId, 2));
            homeworkTaskClassRepository.save(homeworkTaskClassz);
            // 正确率统计 【已经禁用，正确率算法不准确】
            this.stuTaskAccuracy(taskId, classId, studentId);
            // 得分率统计
            this.stuTaskScoreRate(taskId, classId, studentId, total);
            // 知识点状态统计
            this.stuTaskPointRate(taskId, classId, studentId);
        } catch (Exception e) {
        }
    }
    
    @Override
    public void stuTaskScoreRate(String taskId, String classId, String studentId, Integer total) {
        // 本次需要统计试题数量【忽略不要学生作答通知试题】
        total = total == null ? 0 : total;
        // 本次任务的总分【忽略不要学生作答通知试题】
        Integer scoreTotal = total * 5;
        // 得分
        Integer score = 0;
        // 获取本次任务试题的得分
        List<HomeworkTaskReportQues> homeworkTaskReportQuesLst = homeworkTaskReportQuesRepository
                .findByStudentIdAndTaskIdAndClassId(studentId, taskId, classId);
        for (HomeworkTaskReportQues homeworkTaskReportQues : homeworkTaskReportQuesLst) {
            Integer mark = homeworkTaskReportQues.getMark() == null ? 0 : homeworkTaskReportQues.getMark();
            score = score + mark;
        }
        // 计算出得分率
        if (scoreTotal > 0 && score > 0) {
            // 更新学生得分率
            HomeworkTaskReport homeworkTaskReport = homeworkTaskReportRepository
                    .findTop1ByTaskIdAndClassIdAndStudentId(taskId, classId, studentId);
            if (homeworkTaskReport != null) {
                // 计算出得分率，并且乘以100
                Double scoreRate = (score.doubleValue() / scoreTotal.doubleValue()) * 100;
                homeworkTaskReport.setScoreRate(scoreRate);
                homeworkTaskReportRepository.save(homeworkTaskReport);
            }
        }
    }

    @Deprecated
    @Override
    public void stuTaskAccuracy(String taskId, String classId, String studentId) {
        try {
            // 获取非通知类试题，作业试题数量
            Integer total = homeworkTaskQuesRepository.countByTaskIdAndQuesTypeNot(taskId, "2");
            // 学生正确分值占得比重
            Double weight = 0d;
            if (total != null && total > 0) {
                // 获取学生所有答题记录
                List<HomeworkTaskReportQues> homeworkTaskReportQues = homeworkTaskReportQuesRepository
                        .findByStudentIdAndTaskIdAndClassId(studentId, taskId, classId);
                if (homeworkTaskReportQues != null && homeworkTaskReportQues.size() > 0) {
                    for (HomeworkTaskReportQues taskReportQues : homeworkTaskReportQues) {
                        // 排除通知类试题
                        if (taskReportQues.getQuestionType() != null && !taskReportQues.getQuestionType().equals("2")) {
                            // 单选题，多选题
                            if (taskReportQues.getQuestionType().equals("0")
                                    || taskReportQues.getQuestionType().equals("1")) {
                                // 是否正确 0-错误 , 1-正确 （单选，多选）
                                Integer passed = taskReportQues.getPassed();
                                if (passed != null && passed == 1) {
                                    weight++;
                                }
                            }
                            // 填空题，简答题
                            if (taskReportQues.getQuestionType().equals("3")
                                    || taskReportQues.getQuestionType().equals("4")) {
                                // 总分5分，每一分权重占 0.2
                                Integer mark = taskReportQues.getMark();
                                if (mark != null) {
                                    weight = weight + mark.doubleValue() * 0.2;
                                }
                            }
                        }
                    }
                }
            }
            if (total != null && total > 0 && weight > 0) {
                // 更新学生正确率
                HomeworkTaskReport homeworkTaskReport = homeworkTaskReportRepository
                        .findTop1ByTaskIdAndClassIdAndStudentId(taskId, classId, studentId);
                if (homeworkTaskReport != null) {
                    // 计算出正确率，并且乘以100
                    Double accuracy = (weight / total.doubleValue()) * 100;
                    homeworkTaskReport.setRightRate(accuracy);
                    homeworkTaskReportRepository.save(homeworkTaskReport);
                }
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void stuTaskPointRate(String taskId, String classId, String studentId) {
        try {
            // 查询这个学生数据是否生成过
            Integer count = homeworkKnowReportRepository.countByTaskIdAndClassIdAndStudentId(taskId, classId,
                    studentId);
            String schoolId = "";
            // 数据没有生成
            if (count == null || count == 0) {
                // 储存基础知识点
                Map<Integer, String> knowMap = new HashMap<Integer, String>();
                List<Integer> knowAll = new ArrayList<>();
                List<Integer> exactnessKnow = new ArrayList<>();
                // 获取学生所有答题记录
                List<HomeworkTaskReportQues> taskReportQues = homeworkTaskReportQuesRepository
                        .findByStudentIdAndTaskIdAndClassId(studentId, taskId, classId);
                if (taskReportQues != null && taskReportQues.size() > 0) {
                    // 获取学校
                    schoolId = taskReportQues.get(0).getSchoolId();
                    // 数据遍历
                    for (HomeworkTaskReportQues reportQues : taskReportQues) {
                        // 基础知识点
                        List<Integer> knowIds = reportQues.getKnowIdLst();
                        List<String> knowNames = reportQues.getKnowNameLst();
                        if (knowIds != null && knowIds.size() > 0) {
                            for (int i = 0; i < knowIds.size(); i++) {
                                knowMap.put(knowIds.get(i), knowNames.get(i));
                            }
                        }
                        // 所有出现的知识点统计
                        if (knowIds != null && knowIds.size() > 0) {
                            knowAll.addAll(knowIds);
                        }
                        // 正确的知识点统计
                        // ## 单选题,多选题
                        if (reportQues.getQuestionType() != null
                                && (reportQues.getQuestionType().equals("0")
                                        || reportQues.getQuestionType().equals("1"))
                                && reportQues.getPassed() != null && reportQues.getPassed() == 1) {
                            if (knowIds != null && knowIds.size() > 0) {
                                exactnessKnow.addAll(knowIds);
                            }
                        }
                        // ## 填空题,简答题
                        if (reportQues.getQuestionType() != null && (reportQues.getQuestionType().equals("3")
                                || reportQues.getQuestionType().equals("4")) && reportQues.getMark() != null) {
                            if (reportQues.getExactnessKnowIdLst() != null
                                    && reportQues.getExactnessKnowIdLst().size() > 0) {
                                exactnessKnow.addAll(reportQues.getExactnessKnowIdLst());
                            }
                        }
                    }
                }
                // 循环所有知识点
                if (knowMap != null && knowMap.size() > 0) {
                    // list 保存数据使用
                    List<HomeworkKnowReport> homeworkKnowReports = new ArrayList<>();
                    // 生成需要保存的数据
                    Set<Integer> knowIds = knowMap.keySet();
                    for (Integer knowId : knowIds) {
                        // 掌握比率计算
                        double rate = 0d;
                        Integer knowIdTotal = Collections.frequency(knowAll, knowId);
                        Integer exactnessKnowTotal = Collections.frequency(exactnessKnow, knowId);
                        if (knowIdTotal > 0 && exactnessKnowTotal > 0) {
                            rate = (exactnessKnowTotal.doubleValue() / knowIdTotal.doubleValue()) * 100;
                        }
                        // 数据对象
                        HomeworkKnowReport HomeworkKnowReport = new HomeworkKnowReport();
                        HomeworkKnowReport.setClassId(classId);
                        HomeworkKnowReport.setKnowId(knowId);
                        HomeworkKnowReport.setKnowName(knowMap.get(knowId));
                        HomeworkKnowReport.setRate(rate);
                        HomeworkKnowReport.setSchoolId(schoolId);
                        HomeworkKnowReport.setStudentId(studentId);
                        HomeworkKnowReport.setTaskId(taskId);
                        homeworkKnowReports.add(HomeworkKnowReport);
                    }
                    // 数据库保存
                    homeworkKnowReportRepository.save(homeworkKnowReports);
                }
            }
        } catch (Exception e) {
        }
    }

    // 时间转化
    private String getDuration(Integer integer) {
        if (integer == null || integer == null) { return ""; }
        long time = integer;
        long miao = time % 60; // 秒
        time = time / 60; // 转化为 分
        long shi = time / 60; // 抓换为 时
        long fen = time % 60; // 抓换为 分
        return shi + "时" + fen + "分" + miao + "秒";
    }

    private String avatar(String avatar) {
        if (avatar != null && avatar.trim().length() > 0 && !avatar.startsWith("http")) {
            avatar = "http://yxcsp.91yunxiao.com/yxcsp/pull/" + avatar;
        }
        return avatar;
    }

}
